#include "RendererOpenGL.h"
#include <gl\gl.h>    // Header File For The OpenGL32 Library
#include <gl\glu.h>   // Header File For The GLu32 Library
#include "glut.h"     // Header File For The GLUT Library
#include "glm.h"

RendererOpenGL::RendererOpenGL(WNDPROC WndProc) : Renderer(WndProc) {
	hRC = NULL;
	for(int i = 0; i < 10; i++) {
		texturesLoaded[i] = NULL;
		textures[i] = NULL;
	}
}

RendererOpenGL::~RendererOpenGL() {
	// Destructor
}

GLvoid RendererOpenGL::ReSizeScene(int width, int height) {
	// Resize And Initialize The GL Window
	if (height==0) height=1;						// Prevent To Divide By Zero
	glViewport(0,0,(GLsizei)width,(GLsizei)height);	// Reset The Current Viewport
	glMatrixMode(GL_PROJECTION);					// Select The Projection Matrix
	glLoadIdentity();								// Reset The Projection Matrix

	// Calculate The Aspect Ratio Of The Windows
	//FOV original is 45
	//other value was 0.1f
	//last value was 100.0f
	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,1.0f,2000.0f);

	glMatrixMode(GL_MODELVIEW);		// Select The Modelview Matrix
	glLoadIdentity();				// Reset The Modelview Matrix
}

int RendererOpenGL::InitGL(GLvoid) {
	// All Setup For OpenGL Goes Here
	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);				// Black Background
	glClearDepth(1.0f);									// Depth Buffer Setup
	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations
	return TRUE;										// Initialization Went OK
}

void RendererOpenGL::startDrawingScene(void) {
	// Start drawing the scene
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear Screen And Depth Buffer
	glLoadIdentity();									// Reset The Current Modelview Matrix
}

void RendererOpenGL::stopDrawingScene(void) {
	// Stop drawing the scene
	SwapBuffers(hDC); // Swap Buffers (Double Buffering)
}

void RendererOpenGL::KillWindow(void) {
	// Properly Kill The Window
	if (fullscreen) {									// Are We In Fullscreen Mode?
		ChangeDisplaySettings(NULL,0);					// If So Switch Back To The Desktop
		ShowCursor(TRUE);								// Show Mouse Pointer
	}
	if (hRC) {											// Do We Have A Rendering Context?
		if (!wglMakeCurrent(NULL,NULL)) {				// Are We Able To Release The DC And RC Contexts?
			MessageBoxA(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		if (!wglDeleteContext(hRC)) {					// Are We Able To Delete The RC?
			MessageBoxA(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		hRC = NULL;										// Set RC To NULL
	}
	if (hDC && !ReleaseDC(hWnd,hDC)) {			// Are We Able To Release The DC
		MessageBoxA(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hDC = NULL;									// Set DC To NULL
	}
	if (hWnd && !DestroyWindow(hWnd)) {					// Are We Able To Destroy The Window?
		MessageBoxA(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hWnd=NULL;										// Set hWnd To NULL
	}
	if (!UnregisterClassA("OpenGL",hInstance)) {		// Are We Able To Unregister Class
		MessageBoxA(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hInstance=NULL;									// Set hInstance To NULL
	}
}

bool RendererOpenGL::CreateAWindow() {
	GLuint PixelFormat;						// Holds The Results After Searching For A Match
	WNDCLASS wc;							// Windows Class Structure
	DWORD dwExStyle;						// Window Extended Style
	DWORD dwStyle;							// Window Style
	RECT WindowRect;						// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;				// Set Left Value To 0
	WindowRect.right=(long)windowWidth;		// Set Right Value To Requested Width
	WindowRect.top=(long)0;					// Set Top Value To 0
	WindowRect.bottom=(long)windowHeight;	// Set Bottom Value To Requested Height

	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= hInstance;							// Set The Instance
	wc.hIcon			= LoadIcon(NULL, IDI_WINLOGO);			// Load The Default Icon
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
	wc.hbrBackground	= NULL;									// No Background Required For GL
	wc.lpszMenuName		= NULL;									// We Don't Want A Menu
	wc.lpszClassName	= "OpenGL";								// Set The Class Name

	if (!RegisterClass(&wc)) {									// Attempt To Register The Window Class
		MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;											// Return FALSE
	}
	
	if (fullscreen) {											// Attempt Fullscreen Mode?
		DEVMODE dmScreenSettings;								// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= windowWidth;			// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= windowHeight;			// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= bits;					// Selected Bits Per Pixel
		dmScreenSettings.dmFields       = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) {
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
			if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","INFOMGEP",MB_YESNO|MB_ICONEXCLAMATION)==IDYES) fullscreen = false; // Windowed Mode Selected.  Fullscreen = FALSE
			else {
				// Pop Up A Message Box Letting User Know The Program Is Closing.
				MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
				return false;
			}
		}
	}

	if (fullscreen) {											// Are We Still In Fullscreen Mode?
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
		dwStyle=WS_POPUP;										// Windows Style
		ShowCursor(FALSE);										// Hide Mouse Pointer
	}
	else {
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);	// Adjust Window To True Requested Size

	// Create The Window
	if (!(hWnd=CreateWindowEx(	dwExStyle,							// Extended Style For The Window
								"OpenGL",							// Class Name
								windowName,							// Window Title
								dwStyle |							// Defined Window Style
								WS_CLIPSIBLINGS |					// Required Window Style
								WS_CLIPCHILDREN,					// Required Window Style
								0, 0,								// Window Position
								WindowRect.right-WindowRect.left,	// Calculate Window Width
								WindowRect.bottom-WindowRect.top,	// Calculate Window Height
								NULL,								// No Parent Window
								NULL,								// No Menu
								hInstance,							// Instance
								NULL)))								// Dont Pass Anything To WM_CREATE
	{
		KillWindow();								// Reset The Display
		MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		bits,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};
	
	if (!(hDC=GetDC(hWnd))) {					// Did We Get A Device Context?
		KillWindow();								// Reset The Display
		MessageBoxA(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;
	}
	if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) { // Did Windows Find A Matching Pixel Format?
		KillWindow();								// Reset The Display
		MessageBoxA(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;
	}
	if(!SetPixelFormat(hDC,PixelFormat,&pfd)) {	// Are We Able To Set The Pixel Format?
		KillWindow();								// Reset The Display
		MessageBoxA(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;
	}
	if (!(hRC=wglCreateContext(hDC))) {			// Are We Able To Get A Rendering Context?
		KillWindow();								// Reset The Display
		MessageBoxA(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;
	}
	if(!wglMakeCurrent(hDC,hRC)) {				// Try To Activate The Rendering Context
		KillWindow();								// Reset The Display
		MessageBoxA(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;
	}

	ShowWindow(hWnd,SW_SHOW);						// Show The Window
	SetForegroundWindow(hWnd);						// Slightly Higher Priority
	SetFocus(hWnd);									// Sets Keyboard Focus To The Window
	ReSizeScene(windowWidth, windowHeight);		// Set Up Our Perspective GL Screen

	if (!InitGL()) {								// Initialize Our Newly Created GL Window
		KillWindow();								// Reset The Display
		MessageBoxA(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;
	}

	return true;									// Success
}

void RendererOpenGL::drawTriangle(POINT3D corner1, POINT3D corner2, POINT3D corner3, COLOR color){
	glBegin(GL_TRIANGLES);			// Start Drawing A Triangle
		glColor3f( color.r, color.g, color.b);
		glVertex3f( corner1.x, corner1.y, corner1.z);					// Top
		glVertex3f( corner2.x, corner2.y, corner2.z);					// Bottom Left
		glVertex3f( corner3.x, corner3.y, corner3.z);					// Bottom Right
	glEnd();
}
void RendererOpenGL::drawRectangle(POINT3D corner1, POINT3D corner2, POINT3D corner3, POINT3D corner4, COLOR color, bool hollow){
	if(hollow) 
		glBegin(GL_LINE_LOOP);
	else glBegin(GL_QUADS);                      // Draw A Quad
		glColor3f(color.r, color.g, color.b);
		glVertex3f( corner1.x, corner1.y, corner1.z);
		glVertex3f( corner2.x, corner2.y, corner2.z);
		glVertex3f( corner3.x, corner3.y, corner3.z);
		glVertex3f( corner4.x, corner4.y, corner4.z);
	glEnd();
}
void RendererOpenGL::drawLine(POINT3D corner1, POINT3D corner2, COLOR color){
	glBegin(GL_LINES);			// Start Drawing A Line
		glColor3f(color.r, color.g, color.b);
		glVertex3f( corner1.x, corner1.y, corner1.z);
		glVertex3f( corner2.x, corner2.y, corner2.z);
	glEnd();
}

void RendererOpenGL::scale(POINT3D xyzCoordinates)
{
	glScalef(xyzCoordinates.x, xyzCoordinates.y, xyzCoordinates.z );
}

void RendererOpenGL::rotate(ORIENTATION orientation)
{
	glRotatef(orientation.degree, orientation.orientVect.x, orientation.orientVect.y, orientation.orientVect.z );
}

void RendererOpenGL::translate(POINT3D xyzCoordinates)
{
	glTranslatef(xyzCoordinates.x, xyzCoordinates.y, xyzCoordinates.z );
}

void RendererOpenGL::enterContext()
{
	glPushMatrix();
}
void RendererOpenGL::exitContext()
{
	glPopMatrix();
}

int RendererOpenGL::LoadRawFile(LPSTR strName, int nSize, BYTE *pHeightMap, int sizex, int sizey) 
{
	FILE *file = NULL;
	file = fopen( strName, "rb" );

	if (!file)	{
		perror ( "Error: file could not be opened" );
		return -1;
	}
		
	if(pHeightMap != NULL) {
		fread( pHeightMap, 1, nSize, file );
		int result = ferror( file );
		if (result)
			perror ( "Error: Failed To Get Data!" );
		fclose(file);
		return 0;
	}
	else {
			GLuint texture;
			unsigned char *data;
		data = (unsigned char*) malloc(sizex * sizey * 4);

		fread(data, sizex * sizey * 3, 1, file);
		fclose(file);

		glGenTextures(1, &texture); //Make room for our texture
		glBindTexture(GL_TEXTURE_2D, texture); //Tell OpenGL which texture to edit
		//Map the image to the texture
		/*glTexImage2D(GL_TEXTURE_2D,                //Always GL_TEXTURE_2D
						0,                            //0 for now
						GL_RGB,                       //Format OpenGL uses for image
						sizex, sizey,  //Width and height
						0,                            //The border of the image
						GL_RGBA, //GL_RGB, because pixels are stored in RGB format
						GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored
										//as unsigned numbers
						data);               //The actual pixel*/
		gluBuild2DMipmaps(GL_TEXTURE_2D, 3,sizex,sizey, GL_RGB, GL_UNSIGNED_BYTE, data);

		free(data);
		for(int i = 0; i < 10; i++) {
			if(textures[i] == NULL) {
				textures[i] = texture;
				texturesLoaded[i] = (char*) malloc(10);
				strcpy(texturesLoaded[i],strName);
				break;
			}
		}
		return texture; //Returns the id of the texture
	}
}
/*
void RendererOpenGL::drawModel(char modelName[10], float translatex, float translatey, float translatez,double angle)  {
	
	char modelname[20] = "";
	strcat(modelname, modelName);
	strcat(modelname, ".obj");
	GLMmodel *model;
	model = glmReadOBJ(modelname);
	glmUnitize(model);
	glPushMatrix();
		
	glTranslatef(translatex,0.0f,translatez);
	glRotated(angle,0,1,0);
	glEnable(GL_TEXTURE_2D);
	glEnable( GL_NORMALIZE );
	glEnable(GL_FRONT_FACE);
	glScalef(50, 50, 50);
	glmDraw(model, GLM_COLOR);	
	glDisable(GL_TEXTURE_2D);
			
    glPopMatrix();
}
*/
void RendererOpenGL::drawPieceQuad(char * texturename, GLfloat s, GLfloat t, GLfloat r, POINT3D position, ORIENTATION orientation, SCALE scale, int sizex, int sizey, COLOR color) 
{
	GLuint texture = NULL;
	for(int i = 0; i < 10; i++) {
		if(texturesLoaded[i] != NULL) {
			if(!strcmp(texturesLoaded[i],texturename)) {
				texture = textures[i];
				break;
			}
		}
		else break;
	}
	if(texture == NULL) 
		texture = LoadRawFile(texturename, NULL, NULL, sizex, sizey);

	glPushMatrix();

	glColor3f(color.r,color.g,color.b);
	glTranslatef(position.x,position.y,position.z);
	glRotatef(orientation.degree,orientation.orientVect.x,orientation.orientVect.y,orientation.orientVect.z);
	glEnable( GL_TEXTURE_2D );
	glEnable (GL_BLEND);
	glBlendFunc (GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);

	glBindTexture( GL_TEXTURE_2D, texture);
	
	glScalef(scale.x,scale.y,scale.z);
	
	glBegin (GL_QUADS);

	glTexCoord3f (0.0, 0.0, 0.0); glVertex3f (0.0, 0.0, 0.0);
	glTexCoord3f (s, 0.0, 0.0); glVertex3f (s*10, 0.0, 0.0);
	glTexCoord3f (s, t, 0.0); glVertex3f (s*10, t*10, 0.0);
	glTexCoord3f (0.0, t, 0.0); glVertex3f (0.0, t*10, 0.0);
	glEnd();

	glDisable (GL_BLEND);

	glPopMatrix();

	glDisable(GL_TEXTURE_2D);
	//glDeleteTextures( 1, &texture );	
}

void RendererOpenGL::writeOnScreen(std::string s, GLdouble x, GLdouble y, int fontsize, COLOR color) {
	glPushMatrix();
	glColor3f(color.r,color.g,color.b);
	glRasterPos3d(x, y,-10.0f);
	std::string::iterator iend = s.end();
	for (std::string::iterator i = s.begin(); i != iend; i++) {
		if(fontsize == 18) {
			glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *i);
			continue;
		}
		else glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, *i);
	}
	glPushMatrix();
}